package org.game.porker.porker24.controller;

import java.util.List;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.game.porker.porker24.mybatis.pojo.Player;
import org.game.porker.porker24.mybatis.pojo.Porker;
import org.game.porker.porker24.mybatis.pojo.Result;
import org.game.porker.porker24.mybatis.service.PlayerService;
import org.game.porker.porker24.util.ConstantUtil;
import org.game.porker.porker24.util.JavaEval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/game")
public class GameController {
	private static Logger logger = Logger.getLogger(GameController.class);
	@Autowired
	private PlayerService playerService;

	public GameController() {
		// TODO Auto-generated constructor stub
	}
	
	@RequestMapping("/start")
	public String start(HttpServletRequest request, ModelMap modelMap) {
		//check login，可以用其他方式来检查是否登录
		if (request.getSession().getAttribute(
				ConstantUtil.playerInSessionKey) == null) 
		{
			return "redirect:/home/index";	
		}
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(ConstantUtil.currentPorkersPerSession);
		if (obj == null) {
			List<Porker> myPorkers = Porker.getRandom4Porkers();
			session.setAttribute(ConstantUtil.currentPorkersPerSession,
					myPorkers);
			session.setAttribute(ConstantUtil.tryNumber, new Integer(1));
			modelMap.addAttribute("current4Porkers", myPorkers);
			modelMap.addAttribute("tryNumber", new Integer(1));
		} else {
			modelMap.addAttribute("current4Porkers", obj);
			modelMap.addAttribute("tryNumber",
					session.getAttribute(ConstantUtil.tryNumber));
		}
		return "game_start";
	}
	
	@RequestMapping("/cleanCurrent")
	public @ResponseBody String clean(HttpServletRequest request, ModelMap modelMap) {
		//check login，可以用其他方式来检查是否登录
		if (request.getSession().getAttribute(
				ConstantUtil.playerInSessionKey) == null) 
		{
			return "good";	
		}
		request.getSession().removeAttribute(ConstantUtil.currentPorkersPerSession);
		return "good";
	}
	
	@RequestMapping("/do24exp")//?
	public @ResponseBody Result do24(HttpServletRequest request) {
		Result result = new Result();
		if (request.getSession().getAttribute(
				ConstantUtil.playerInSessionKey) == null) 
		{
			result.setMessage("没有登录或者超时");
			result.setTryNumber(Integer.MAX_VALUE);
			return result;	
		}
		Integer tryNumber = (Integer)request.getSession().getAttribute(ConstantUtil.tryNumber);
		if(tryNumber == null) {
			tryNumber = 1;
		} else {
			tryNumber = Integer.valueOf(tryNumber.intValue() + 1);
		}
		logger.debug("trynumber=" + tryNumber);
		request.getSession().setAttribute(ConstantUtil.tryNumber, tryNumber);
		result.setTryNumber(tryNumber);
		String exp = request.getParameter("24exp");
		if (exp == null || exp.trim().equals("")) {
			result.setMessage("没有任何表达式");
//			return result;
		} else {
			exp = exp.trim() + "#";
			logger.debug("exp=" + exp);
			try {
				String out = JavaEval.eval(exp);
				if (out.equals("24")) {
					result.setPass(true);
					
				} else {
					result.setPass(false);
					result.setMessage("计算结果不是24，是" + out);
				}
			} catch (Exception e) {
				result.setPass(false);
				result.setMessage(e.getMessage());
			}
		}
		if(result.isPass()) {
			exp = exp.replaceAll("-", "+");
			exp = exp.replaceAll("\\*", "+");
			exp = exp.replaceAll("/", "+");
			String count = JavaEval.eval(exp);
			Player p = (Player)request.getSession().getAttribute(
					ConstantUtil.playerInSessionKey);
			playerService.insertGameAndUpdateScore(p.getPlayerId(), 
					Integer.valueOf(count));
			request.getSession().removeAttribute(ConstantUtil.currentPorkersPerSession);
		} else if(result.getTryNumber() > 3) {
			String count = "0";
			Player p = (Player)request.getSession().getAttribute(
					ConstantUtil.playerInSessionKey);
			playerService.insertGameAndUpdateScore(p.getPlayerId(), 
					Integer.valueOf(count));
			request.getSession().removeAttribute(ConstantUtil.currentPorkersPerSession);
		}
//		Set a = new TreeSet();
		return result;
	}

}
